<?php

/**
 * Class that represent an entity with fields and values.
 * 
 * You can access values like if they were properties of this class.
 */
class Cameo_Data_Entity {
	
	/**
	 * @var array values indexed by their field name
	 */
	private $_values = array();
	
	/**
	 * Construct the entity with its columns and optionnaly their initialisation
	 * values
	 *
	 * By default, values that aren't initialized are set to null
	 *
	 * @param array $fields List of the fields that this entity have
	 * @param array $values Values of the entity at initialisation
	 */
	public function __construct(array $fields, array $values = array()) {
		foreach ($fields as $field_name) {
			$this->_values[$field_name] = isset($values[$field_name]) ? $values[$field_name] : null;
		}
	}
	
	/**
	 * Read an entity value with a field name
	 *
	 * @param string $field_name Field name to access
	 * @return mixed
	 */
	public function __get($field_name) {
		if (!isset($this->_values[$field_name])) {
			throw new InvalidArgumentException('There is no property called "' . $field_name . '"');
		}
		
		return $this->_values[$field_name];
	}
	
	/**
	 * Write an entity value with a field name and a value (obviously)
	 *
	 * @param string $field_name Field name to access
	 * @param string $value Value to set to the field
	 */
	public function __set($field_name, $value) {
		if (!isset($this->_values[$field_name])) {
			throw new InvalidArgumentException('There is no property called "' . $field_name . '"');
		}
		
		$this->_values[$field_name] = $value;
	}
	
	/**
	 * Access to the list of the field names that this entity is initialized
	 * 
	 * @return array list of field names
	 */
	public function getFieldNames() {
		return array_keys($this->_values);
	}
	
	/**
	 * Get the values of this entity indexed by their field name
	 *
	 * @return array
	 */
	public function toArray() {
		return $this->_values;
	}
	
	/**
	 * Set values of this entity in a batch
	 * 
	 * When values aren't setted for a field, it is automatically reset to null
	 * 
	 * @todo see if it's correct to reset all the values
	 *
	 * @param array $values Values to set in the entity
	 * @return array
	 */
	public function setValues($values) {
		foreach ($this->_values as $field_name => $value) {
			$this->_values[$field_name] = isset($values[$field_name]) ? $values[$field_name] : null;
		}
	}
	
}